package com.chainyoung.common.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.airbnb.lottie.LottieAnimationView;
import com.chainyoung.common.R;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.mvp.BasePresenter;
import com.chainyoung.common.utils.ToastUtil;
import com.google.gson.JsonObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static com.chainyoung.common.constant.CommonStringConstants.TITLE;
import static com.chainyoung.common.constant.CommonStringConstants.URL;

public abstract class WebViewActvity<P extends BasePresenter> extends BaseActivity<P> {


    protected WebView mWebView;
    protected LottieAnimationView mLottieAnimationView;

    protected String url;

    protected String html;

    protected String address = "";


    private ValueCallback<Uri> mUploadMessage;//回调图片选择，4.4以下
    private ValueCallback<Uri[]> mUploadCallbackAboveL;//回调图片选择，5.0以上
    private static final int FILE_SELECT_CODE = 0;



    @Override
    protected void initUI() {
        mWebView = findViewById(R.id.webView);
        mLottieAnimationView = findViewById(R.id.LottieAnimationView);
        url = getIntent().getStringExtra(URL);
        initSetting();



    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_web_view;
    }


    @SuppressLint("NewApi")
    private void initSetting() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);//图片自动缩放 打开
        } else {
            webSettings.setLoadsImagesAutomatically(false);//图片自动缩放 关闭
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码
        }
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码

        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
//        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setSupportZoom(true);// 设置可以支持缩放
        webSettings.setBuiltInZoomControls(true);// 设置出现缩放工具 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false

        webSettings.setDisplayZoomControls(false);//隐藏缩放工具
        webSettings.setUseWideViewPort(true);// 扩大比例的缩放
        //mWebView.getSettings().setDefaultFontSize(40);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setSupportMultipleWindows(true);//支持多窗口

        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);

        webSettings.setDatabaseEnabled(true);//
        webSettings.setSavePassword(true);//保存密码
        webSettings.setDomStorageEnabled(true);//是否开启本地DOM存储  鉴于它的安全特性（任何人都能读取到它，尽管有相应的限制，将敏感数据存储在这里依然不是明智之举），Android 默认是关闭该功能的。
        mWebView.setSaveEnabled(true);
        mWebView.setKeepScreenOn(true);

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        mWebView.setWebViewClient(new WebViewClient());


        // 设置setWebChromeClient对象
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);

            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                mLottieAnimationView.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_SELECT_CODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILE_SELECT_CODE);
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_SELECT_CODE);

            }

            // For Android 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILE_SELECT_CODE);
                return true;
            }


        });
        //设置此方法可在WebView中打开链接，反之用浏览器打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
                mLottieAnimationView.setVisibility(View.GONE);
                // mWebView.loadUrl("javascript:" + jsStr);
//                if (Build.VERSION.SDK_INT >= 19) {
//                    mWebView.evaluateJavascript(jsStr, new ValueCallback<String>() {
//                        @Override public void onReceiveValue(String value) {//js与native交互的回调函数
//                            Log.d("webview", "value=" + value);
//                        }
//                    });
//                }

            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                mLottieAnimationView.setVisibility(View.VISIBLE);

                super.onPageStarted(view, url, favicon);

            }

//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
////                if ((url.startsWith("http:") || url.startsWith("https:"))) {
////                    view.loadUrl(url);
////                    return false;
////                }
////                if (url.equals(ServerConstant.BMGAME_DOWNLOAD)) {
////                    if (AppUtils.isInstallApp(mContext, PkgName.BM_GAME.pkgName)) {
////                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ServerConstant.BM_URI));
////                        startActivity(intent);
////                    }
////                }
//                return true;
//            }
        });
        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }

        mWebView.addJavascriptInterface(new JavaScriptinterface(this),
                "android");


    }


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }

    }


    class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void onFinish() {
            finish();
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            if (Build.VERSION.SDK_INT >= 21) {//5.0以上版本处理
                mUploadCallbackAboveL.onReceiveValue(null);//回调给js
            } else {
                //4.4以下处理
                mUploadMessage.onReceiveValue(null);
            }
            return;
        }

        switch (requestCode) {
            case FILE_SELECT_CODE: {
                if (Build.VERSION.SDK_INT >= 21) {//5.0以上版本处理
                    Uri uri = data.getData();
                    Uri[] uris = new Uri[]{uri};
                   /* ClipData clipData = data.getClipData();  //选择多张
                    if (clipData != null) {
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            Uri uri = item.getUri();
                            uris[i]=uri;
                        }
                    }*/
                    mUploadCallbackAboveL.onReceiveValue(uris);//回调给js
                } else {//4.4以下处理
                    Uri uri = data.getData();
                    mUploadMessage.onReceiveValue(uri);
                }


            }
            break;
        }
    }

    /**
     * 获取到Dapp 交易数据
     * @param transactionInfo
     */
    protected void getWebTransactionInfo(String transactionInfo) {


    }


    @Override
    protected void onResume() {
        super.onResume();
        // mWebView.onResume();
        // mWebView.pauseTimers();

    }

    @Override
    protected void onPause() {
        super.onPause();
        // mWebView.onPause();
        // mWebView.resumeTimers();
    }
}
